//
//  SignUpViewModel.swift
//  RXmvvmDemo
//
//  Created by jemi on 2020/1/2.
//  Copyright © 2020 jemi. All rights reserved.
//

import RxSwift
import RxCocoa

class SignUpViewModel {
    let validatedUsername: Driver<ValidationResult>
    let validatedPassword: Driver<ValidationResult>
    let validatedPasswordRepeate: Driver<ValidationResult>
    let signupEnable: Driver<Bool>
    let signUpResult: Driver<Bool>
    
    init(
        input:(
        username: Driver<String>,
        password: Driver<String>,
        repeatePassword: Driver<String>,
        loginTags: Signal<Void>
        ),
        dependency:(
        networkService: NetWorkService,
        signUpService: SignupService
        )
    ) {
        
        validatedUsername = input.username
            .flatMapLatest{ username in
                return dependency.signUpService.validateUsername(username).asDriver(onErrorJustReturn: .failed(message: "服务器发生错误!"))
            }
        
        validatedPassword = input.password
            .map{ password in
                return dependency.signUpService.validatePassword(password)
        }
        
        validatedPasswordRepeate = Driver.combineLatest(
            input.password,
            input.repeatePassword,
            resultSelector: dependency.signUpService.validateRepeatedPassword
        )
        
        signupEnable = Driver.combineLatest(
            validatedUsername,
            validatedPassword,
            validatedPasswordRepeate
        ) { username, password, repeatePassword in
            username.isValid && password.isValid &&
            repeatePassword.isValid
        }.distinctUntilChanged()
        
        
        let usernameAndPassword = Driver.combineLatest(input.username,input.password){
            (username: $0, password: $1)
        }
        
        signUpResult = input.loginTags.withLatestFrom(usernameAndPassword).flatMapLatest{ pair in
            return dependency.networkService.signup(pair.username, password: pair.password).asDriver(onErrorJustReturn: false)
            
        }
        
    }
}
